<?php
namespace Wechat\Controller;

use Base\Controller\HomeBaseController;
use Org\Wechat\WechatAuth;

class WxCustomerBaseController extends HomeBaseController {
    
	protected $customerModel;
	protected $customer;
	
	function _initialize() {
		parent::_initialize();
        
		$this->_checkLogin();
	//	$this->_checkCustomerStatus();
	
		$openid = session('weixinUserInfo.openid');
		if ($openid) {
			$this->customerModel = D("Customer/Customer");
			$this->customer = $this->customerModel->where(array("open_id" => $openid))->find();
		}
		
// 		$this->customerModel = D("Customer/Customer");                                    // ---
// 		$this->customer = $this->customerModel->where(array("id" => 7))->find();          // ---
	}
	
	/**
	 * 检查微信用户登录
	 */
	protected function _checkLogin() {
	    $sessionCustomer = session('weixinUserInfo');
		if (!empty($sessionCustomer)) {
		    return;
		}

		$wxSetting = M('WxSetting')->where(array("id" => "1"))->find();
		$auth = new WechatAuth($wxSetting['appid'], $wxSetting['appsecret']);
		
		$code = $_GET['code'];
		if ($code == null) {
//          $redirect_uri = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];   // 此即为本页面地址
		    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];   // 此即为本页面地址
            $state = 'STATE';
            $requestCodeURL = $auth->getRequestCodeURL($redirect_uri, $state);
		    header("Location:" . $requestCodeURL);
		    return;
		}

	    $accessToken = $auth->getAccessToken('code', $code);

	    $userInfo = $auth->getUserInfoExt($accessToken['openid'], $accessToken['access_token']);                    // 通过全局access_token获取用户基本信息 未关注是array('subscribe'=>0,'openid')
// 		dump($userInfo);
	    session('weixinUserInfo', $userInfo);
	    return;
	}
	
	/**
	 * 检查微信用户状态
	 */
	protected function _checkCustomerStatus() {
	    $sessionCustomerId = session('CUSTOMER.id');
	    $status = M('Customer')->where(array("id" => $sessionCustomerId))->getField("status");
	    if ($status != 1) {
			if ($status == -1 || $status == -2) {
				$this->error(L('USERNAME_NOT_EXIST_OR_FORBIDDEN'), __ROOT__ . "/");
			} else if ($status == 0 || $status == 2) {
				$this->assign("messageTitle", "账号未认证！");
				$this->error('您还没有通过账号认证，请认证后再使用！', U("Customer/Login/auth"));
			} else if ($status == 3) {
				$this->assign("messageTitle", "等待认证中！");
				$this->error('等待认证中，请通过认证后再进入！');
			}
	    }
	}
	
}